package cn.eoeit.mmy.controller;



import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.eoeit.mmy.bean.RespCode;
import cn.eoeit.mmy.bean.Response;
import cn.eoeit.mmy.model.UserInfo;
import cn.eoeit.mmy.service.ISessionService;
import cn.eoeit.mmy.service.IUserService;
import cn.eoeit.mmy.util.SysUtils;

@Controller
@RequestMapping("/index")
public class IndexController {

	@Autowired
	private IUserService userService;	
	
	@Autowired
	private ISessionService sessionService;
	
	@RequestMapping(value ="/finishLogin")
	
	public  @ResponseBody Response finishLogin(@RequestBody UserInfo user,HttpServletRequest request){
		
		Response response=Response.getSuccess();
		user =userService.finishLogin(user);
		if(user!=null){
			sessionService.storeLoginInfo(request, user);
		}else{
			response.setCode(RespCode.USER_ERROR);
			response.setMessage("用户名或者密码错误");      
		}  
		
		return response;
	}
	
	
	@RequestMapping(value ="/loginOut")
	public String loginOut(ModelMap modelMap,  HttpServletRequest request){
		
		sessionService.clear(request);
		
		return "/login";
	}
	
	@RequestMapping(value ="/login")
	public String login(ModelMap modelMap,  HttpServletRequest request){
		
		sessionService.clear(request);
		
		return "/login";
	}
	/**
	 * 获取验证码（登录用）
	 * 
	 * @param response
	 */
	@RequestMapping("/getRandCodeImg")
	public void getRandCodeImg(HttpServletResponse response, HttpServletRequest request) {

		// 设置页面不缓存数据
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 获取4位随机验证码
		char[] randNum = SysUtils.getRandNum(4);
		String randNumStr = new String(randNum);

		// 将验证码存入session
		request.getSession().setAttribute("imageCode", randNumStr);
		Cookie cookie = new Cookie("imageCode", randNumStr);

		response.addCookie(cookie);

		// 生成验证码图片
		BufferedImage image = SysUtils.generateRandImg(randNum);

		try {// 输出图象到页面
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException ioEx) {
			// logger.error("验证码图片显示异常", ioEx);
		}
	}
}